<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>字典配置</span>
          <div>
            <el-button type="primary" @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 调试信息 -->
        <div style="margin-bottom: 15px">
          <p>组件已加载 | 配置数量: {{ configList.length }}</p>
        </div>

        <el-table :data="configList" border style="width: 100%">
          <el-table-column prop="description" label="描述" min-width="80" />
          <el-table-column prop="config_key" label="配置键名" min-width="80" />

          <el-table-column prop="value_type" label="值类型" width="100">
            <template #default="scope">
              <el-tag :type="getTypeTag(scope.row.value_type)">{{
                scope.row.value_type
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="group_name" label="分组" width="120" />
          <el-table-column prop="config_value" label="配置值" min-width="180" />
          <el-table-column prop="is_public" label="是否公开" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.is_public ? 'success' : 'info'">
                {{ scope.row.is_public ? "是" : "否" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
                :disabled="userStore.isTest"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
                :disabled="userStore.isTest"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="op-toolbar">
          <el-button
            type="success"
            @click="handleAdd"
            :disabled="userStore.isTest"
            >添加配置</el-button
          >
        </div>
      </div>
    </el-card>

    <!-- 表单对话框 -->
    <el-dialog
      :title="editMode ? '编辑配置' : '添加配置'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="配置键名" prop="config_key">
          <el-input
            v-model="form.config_key"
            placeholder="请输入配置键名"
            :disabled="editMode"
          />
        </el-form-item>
        <el-form-item label="配置值" prop="config_value">
          <template v-if="form.value_type === 'json'">
            <VAceEditor
              v-model:value="aceJsonStr"
              lang="json"
              :theme="aceConfig.theme"
              :options="aceConfig.options"
              :readonly="aceConfig.readOnly"
              style="height: 300px; width: 100%"
              class="ace-editor"
            />
          </template>

          <template v-else-if="form.value_type === 'boolean'">
            <el-switch v-model="form.config_value" />
          </template>

          <template v-else>
            <el-input
              v-model="form.config_value"
              :type="form.value_type === 'text' ? 'textarea' : 'text'"
              :rows="3"
              placeholder="请输入配置值"
            />
          </template>
        </el-form-item>

        <el-form-item label="值类型" prop="value_type">
          <el-select v-model="form.value_type" placeholder="请选择值类型">
            <el-option label="字符串" value="string" />
            <el-option label="数字" value="number" />
            <el-option label="布尔值" value="boolean" />
            <el-option label="文本" value="text" />
            <el-option label="JSON" value="json" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组" prop="group_name">
          <el-select
            v-model="form.group_name"
            placeholder="请选择分组"
            filterable
            allow-create
          >
            <el-option label="基础设置" value="基础设置" />
            <el-option label="业务设置" value="业务设置" />
            <el-option label="注册设置" value="注册设置" />
            <el-option label="支付设置" value="支付设置" />
            <el-option label="其他设置" value="其他设置" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="是否公开">
          <el-switch v-model="form.is_public" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/store/user";
import {
  getSystemConfigs,
  addConfig,
  updateConfig,
  deleteConfig,
  resetConfigs,
} from "@/api/configs";
import { useRouter } from "vue-router";

// 导入模块
import { VAceEditor } from "vue3-ace-editor";
import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-chrome";
import "ace-builds/src-noconflict/ext-language_tools";
const aceJsonStr = ref("");
// 表单数据
const form = reactive({
  config_key: "",
  config_value: "",
  value_type: "string",
  group_name: "基础设置",
  description: "",
  is_public: false,
});
watch(
  () => form.config_value,
  (val) => {
    if (form.value_type === "json") {
      try {
        aceJsonStr.value =
          typeof val === "string"
            ? JSON.stringify(JSON.parse(val), null, 2)
            : JSON.stringify(val, null, 2);
      } catch {
        aceJsonStr.value = typeof val === "string" ? val : JSON.stringify(val);
      }
    }
  },
  { immediate: true }
);

watch(
  () => aceJsonStr.value,
  (val) => {
    if (form.value_type === "json") {
      form.config_value = val;
    }
  }
);
//ace编辑器配置
const aceConfig = reactive({
  lang: "json", //解析json
  theme: "chrome", //主题
  arr: [
    /*所有主题*/
    "ambiance",
    "chaos",
    "chrome",
    "clouds",
    "clouds_midnight",
    "cobalt",
    "crimson_editor",
    "dawn",
    "dracula",
    "dreamweaver",
    "eclipse",
    "github",
    "gob",
    "gruvbox",
    "idle_fingers",
    "iplastic",
    "katzenmilch",
    "kr_theme",
    "kuroir",
    "merbivore",
    "merbivore_soft",
    "monokai",
    "mono_industrial",
    "pastel_on_dark",
    "solarized_dark",
    "solarized_light",
    "sqlserver",
    "terminal",
    "textmate",
    "tomorrow",
    "tomorrow_night",
    "tomorrow_night_blue",
    "tomorrow_night_bright",
    "tomorrow_night_eighties",
    "twilight",
    "vibrant_ink",
    "xcode",
  ],
  readOnly: false, //是否只读
  options: {
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true,
    tabSize: 2,
    showPrintMargin: false,
    fontSize: 13,
  },
});
const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const dialogVisible = ref(false);
const editMode = ref(false);
const formRef = ref(null);

// 模拟配置数据
const configList = ref([]);

// 表单验证规则
const rules = {
  config_key: [{ required: true, message: "请输入配置键名", trigger: "blur" }],
  config_value: [{ required: true, message: "请输入配置值", trigger: "blur" }],
  value_type: [{ required: true, message: "请选择值类型", trigger: "change" }],
  group_name: [{ required: true, message: "请选择分组", trigger: "change" }],
};

// 获取类型标签颜色
const getTypeTag = (type) => {
  const typeMap = {
    string: "",
    number: "success",
    boolean: "warning",
    text: "info",
    json: "danger",
  };
  return typeMap[type] || "";
};

// 刷新数据 - 修复版本
const handleRefresh = async () => {
  loading.value = true;
  try {
    const res = await getSystemConfigs();
    if (res.code === 0) {
      // 处理后端返回的数据结构
      configList.value = (res.data || []).map((item) => {
        // 增强的数据映射逻辑，处理不同的字段名
        const mappedItem = {
          config_key: item.key || item.config_key,
          config_value:
            typeof item.value !== "undefined"
              ? item.value
              : item.config_value || "",
          value_type: item.type || item.value_type || "string",
          group_name: item.group || item.group_name || "其他设置",
          description: item.description || "",
          is_public:
            typeof item.is_public !== "undefined" ? item.is_public : true,
        };
        return mappedItem;
      });
      ElMessage.success("刷新成功");
    } else {
      ElMessage.error(res.message || "获取配置失败");
      // 使用静态数据作为后备
      useStaticData();
    }
  } catch (error) {
    console.error("获取配置失败", error);
    ElMessage.error("获取配置失败，使用静态数据");
    // 使用静态数据作为后备
    useStaticData();
  } finally {
    loading.value = false;
  }
};

// 使用静态数据作为后备
const useStaticData = () => {
  configList.value = [
    {
      config_key: "site_name",
      config_value: "学法减分题库",
      value_type: "string",
      group_name: "基础设置",
      description: "网站名称",
      is_public: true,
    },
    {
      config_key: "register_enabled",
      config_value: "true",
      value_type: "boolean",
      group_name: "注册设置",
      description: "是否允许用户注册",
      is_public: true,
    },
    {
      config_key: "daily_free_count",
      config_value: "3",
      value_type: "number",
      group_name: "业务设置",
      description: "每日免费使用次数",
      is_public: true,
    },
  ];
};

// 添加配置
const handleAdd = () => {
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能添加配置");
    return;
  }

  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 编辑配置
const handleEdit = (row) => {
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能编辑配置");
    return;
  }

  editMode.value = true;
  resetForm();

  // 复制数据到表单
  Object.keys(form).forEach((key) => {
    if (key in row) {
      form[key] = row[key];
    }
  });

  dialogVisible.value = true;

  // 👇 如果是 JSON，手动同步到 aceJsonStr
  if (form.value_type === "json") {
    try {
      aceJsonStr.value =
        typeof form.config_value === "string"
          ? JSON.stringify(JSON.parse(form.config_value), null, 2)
          : JSON.stringify(form.config_value, null, 2);
      console.log("aceJsonStr:", JSON.stringify(form.config_value));
    } catch {
      console.log("aceJsonStr:", JSON.stringify(form.config_value));
      aceJsonStr.value = String(form.config_value);
    }
  }
};

// 删除配置
const handleDelete = (row) => {
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能删除配置");
    return;
  }

  ElMessageBox.confirm(`确认删除配置 "${row.config_key}" 吗？`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        loading.value = true;
        const res = await deleteConfig(row.config_key);
        if (res.code === 0) {
          // 从列表中移除该项
          const index = configList.value.findIndex(
            (item) => item.config_key === row.config_key
          );
          if (index !== -1) {
            configList.value.splice(index, 1);
          }
          ElMessage.success("删除成功");
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error) {
        console.error("删除配置失败", error);
        ElMessage.error("删除失败，请重试");
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {});
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  form.config_key = "";
  form.config_value = "";
  form.value_type = "string";
  form.group_name = "基础设置";
  form.description = "";
  form.is_public = false;
};

// 提交表单
const submitForm = async () => {
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能修改配置");
    return;
  }

  formRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    // 创建新对象来匹配后端API期望的格式
    const newConfig = {
      config_key: form.config_key,
      value: form.config_value, // 后端API中使用的是value而非config_value
      type: form.value_type, // 后端API中使用的是type而非value_type
      group: form.group_name, // 后端API中使用的是group而非group_name
      description: form.description,
      is_public: form.is_public,
    };

    try {
      loading.value = true;

      if (editMode.value) {
        // 更新现有配置
        const res = await updateConfig(form.config_key, newConfig);
        if (res.code === 0) {
          // 更新前端列表
          const index = configList.value.findIndex(
            (item) => item.config_key === form.config_key
          );
          if (index !== -1) {
            // 保持前端字段命名一致
            configList.value[index] = {
              config_key: form.config_key,
              config_value: form.config_value,
              value_type: form.value_type,
              group_name: form.group_name,
              description: form.description,
              is_public: form.is_public,
            };
          }
          ElMessage.success("更新成功");
          dialogVisible.value = false;
        } else {
          ElMessage.error(res.message || "更新失败");
        }
      } else {
        // 添加新配置
        const res = await updateConfig(form.config_key, newConfig);
        if (res.code === 0) {
          // 保持前端字段命名一致
          configList.value.push({
            config_key: form.config_key,
            config_value: form.config_value,
            value_type: form.value_type,
            group_name: form.group_name,
            description: form.description,
            is_public: form.is_public,
          });
          ElMessage.success("添加成功");
          dialogVisible.value = false;
        } else {
          ElMessage.error(res.message || "添加失败");
        }
      }
    } catch (error) {
      console.error("保存配置失败", error);
      ElMessage.error("操作失败，请重试");
    } finally {
      loading.value = false;
    }
  });
};

onMounted(() => {
  handleRefresh();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.op-toolbar {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
